<script setup>
import {reactive, ref,onMounted} from 'vue'
import {Delete, Edit, Search} from '@element-plus/icons-vue'
import formView from './formView.vue';
import {ElMessage, ElMessageBox} from "element-plus";
import DispatchForm from './DispatchForm.vue'
import { get, post, put, del } from '@/api/request'
import {getTextByCode, getCodeByText, getDictOptions} from '@/utils/dictionaryUtil';
// 控制对话框显示状态
const showStudentDetail = ref(false);
// 选中的学生数据
const selectedStudent = reactive({
  // 学生详细信息
});

// 处理对话框关闭事件
const handleFormClose = () => {
  console.log('对话框已关闭');
  // 可以执行其他操作
};
// 模拟学校数据
const schoolData =  ref([])

const getSchoolData = async () => {
  try {
    // 直接使用get方法请求用户信息API
    const data = await get('/api/system/odi/child/student/all', {})

    schoolData.value = [data.rows]
    console.log(data.rows)
  } catch (error) {
    console.error('获取数据失败：', error)
  }
}
onMounted(() => {
   getSchoolData()
})


// 分页相关数据
const pagination = reactive({
  pageNum: 1,
  pageSize: 15,
  total: 0
})

// 模拟学生数据 - 生成20条随机记录
const studentData = ref([])

// 搜索表单
const searchForm = reactive({
  nameOrId: '',
  idCard: '',
  status: '',
  studentType: ''
})

// 当前选中的树节点
const currentNode = ref('')

// 表格列定义
const columns = [
  {prop: 'avatar', label: '人脸照片', width: 120},
  {prop: 'name', label: '学生姓名', 'min-width': 120},
  {prop: 'userNo', label: '学号', 'min-width': 120},
  {prop: 'gender', label: '性别', 'min-width': 80},
  {prop: 'grade', label: '所属班级', 'min-width': 180},
  {prop: 'zkzh', label: '准考证号', 'min-width': 120},
  {prop: 'type', label: '类型', 'min-width': 100},
  {prop: 'joinDate', label: '入学日期', 'min-width': 120},
  {prop: 'realName', label: '实名状态', 'min-width': 100}
]

// 状态选项
const statusOptions = [
  {value: '', label: '请选择实名状态'},
  {value: '1', label: '已实名'},
  {value: '0', label: '未实名'}
]

// 学生类型选项
const studentTypeOptions = [
  {value: '', label: '学生类型'},
  {value: '1', label: '非晚自习通校生'},
  {value: '2', label: '晚自习通校生'},
  {value: '3', label: '住校生'}
]

// 获取学生列表数据
const getStudentList = async (departId) => {
  try {
    const params = {
      departId: departId || (currentNodeData.value ? currentNodeData.value.id : ''),
      option: searchForm.idCard || '',
      isRealName: searchForm.status || null,
      studentType: searchForm.studentType || null,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    }

    const res = await post('/api/system/uis/page', params)
    if (res && res.rows) {
      studentData.value = res.rows
      pagination.total = res.total || 0
    } else {
      studentData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取学生列表失败：', error)
    studentData.value = []
    pagination.total = 0
  }
}

// 删除学生
const deleteStudent = (student) => {
  if (!student.id) {
    ElMessage.warning('无法识别要删除的学生ID')
    return
  }

  ElMessageBox.confirm(
    '确定要删除此学生信息吗？删除后无法恢复。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      // 调用删除学生API
      await del(`/api/system/uis/remove/${student.id}`)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      // 重新获取学生列表数据
      getStudentList()
    } catch (error) {
      console.error('删除学生失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  })
  .catch(() => {
    // 用户取消删除，不做任何操作
  })
}

// 处理节点点击
const handleNodeClick = (data) => {
  currentNode.value = data.departName
  currentNodeData.value = data
  pagination.pageNum = 1 // 重置为第一页

  getStudentList(data.id)
}

// 处理页码变化
const handleCurrentChange = (val) => {
  pagination.pageNum = val
  getStudentList()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.pageNum = 1
  getStudentList()
}

// 处理查询按钮点击
const handleSearch = () => {
  if (currentNodeData.value) {
    pagination.pageNum = 1
    getStudentList()
  } else {
    ElMessage.warning('请选择左侧班级')
  }

}

// 子架构对话框相关数据
const structureDialogVisible = ref(false)
const structureDialogTitle = ref('')
const structureForm = reactive({
  name: '',
  parentId: null
})
const structureDialogType = ref('') // 'add' 或 'rename'
const currentNodeData = ref(null)
const rowId = ref(null)
// 添加学生
const addStudent = (e) => {
  console.log('添加学生')
  if (currentNodeData.value) {
    isEditor.value = true;
  } else {
    ElMessage.warning('请选择左侧班级')
  }
}
// 导入数据
const importData = () => {
  console.log('导入数据')
  dialogFormVisible.value=true
}

// 人员调度
const transferPersonnel = () => {
  console.log('人员调度')
  DispatchVisible.value=true
}

// 新增子架构
const addStructure = (node) => {
  structureDialogType.value = 'add'
  structureDialogTitle.value = '新增子架构'
  structureForm.name = ''
  structureForm.parentId = node.data.id
  currentNodeData.value = node.data
  structureDialogVisible.value = true
}

// 删除子架构
const deleteStructure = (node) => {
  const nodeId = node.data ? node.data.id : node.id

  if (!nodeId) {
    ElMessage.warning('无法识别要删除的架构ID')
    return
  }

  ElMessageBox.confirm(
    '确定要删除此架构吗？删除后无法恢复。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true,
    }
  )
  .then(async () => {
    try {
      // 调用删除架构API
      await del(`/api/system/odi/remove/${nodeId}`)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      // 重新获取架构数据
      await getSchoolData()
    } catch (error) {
      console.error('删除失败:', error)
      // ElMessage.error('删除失败，请重试')
    }
  })
  .catch(() => {})
}

// 重命名
const rename = (node) => {
  structureDialogType.value = 'rename'
  structureDialogTitle.value = '重命名子架构'
  structureForm.name = node.label
  currentNodeData.value = node.data
  structureDialogVisible.value = true
}

// 处理架构对话框提交
const handleStructureSubmit = async () => {
  if (!structureForm.name.trim()) {
    ElMessage.warning('名称不能为空')
    return
  }

  try {
    if (structureDialogType.value === 'add') {
      // 调用新增子架构API
      await post('/api/system/odi/addStudentDept', {
        parentId: structureForm.parentId,
        departName: structureForm.name
      })
      ElMessage.success('添加成功')
    } else if (structureDialogType.value === 'rename') {
      // 调用重命名架构API
      await put('/api/system/odi/rename', {
        id: currentNodeData.value.id,
        departName: structureForm.name
      })
      ElMessage.success('重命名成功')
    }
    // 重新获取架构数据
    await getSchoolData()
    structureDialogVisible.value = false
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

const showPreview = ref(false)
// 编辑学生信息
const editStudent = (student) => {
  console.log(student)
  console.log('编辑学生')
  rowId.value = student.id
  isEditor.value = true;
}
const imageRef = ref()
const handleClick = (e) => {
  showPreview.value = true
  imageRef.value = e
}
const isEditor = ref(false)
const dialogFormVisible=ref(false)
const DispatchVisible=ref(false)
</script>

<template>
  <div class="">
     <div v-if="isEditor" >
       <div style="padding: 15px;background-color: white">
         <el-button type="primary" @click="() => {isEditor=false; getStudentList();rowId=''}"> 返回</el-button>
       </div>
       <div style="padding:20px">
         <formView  @on-cancel="rowId='';isEditor=false"
                   v-model:visible="showStudentDetail"
                   :rowId="rowId"
                   :zuzhiId="currentNodeData.id"
         /></div>

     </div>
    <!-- 主要内容区 -->
    <div class="main-content-table" v-else>

      <!-- 左侧树形结构 -->
      <div class="tree-container sudtree">
        <el-tree
            :data="schoolData"
            :props="{
               children: 'childs',
               label: 'departName',
            }"

            node-key="id"
            @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <div class="custom-tree-node"  >
              <div style="display: flex;align-items: center;gap: 5px">
                <div class="svg-icon-wrapper">
                  <img src="@/assets/images/tree.svg" alt="操作图标" class="svg-icon"/>
                </div>
                <el-text truncated>{{ node.label }}</el-text>
               </div>
              <div>
                <el-popover
                    placement="top-start"
                    :width="200"
                    trigger="click"
                    stop-popper-mouse-event
                >
                  <template #reference>

                    <el-icon style="width: 35px;text-align: center;">
                      <More style="left: -12px;position: relative;"/>
                    </el-icon>
                  </template>
                  <div class="popStr">
                  <div @click="rename(node)">重命名</div>
                  <div @click="addStructure(node)">增加子架构</div>
                  <div @click="deleteStructure(node)" style="color: red">删除此架构</div>
                  </div>
                </el-popover>


              </div>
            </div>
          </template>
        </el-tree>
      </div>
      <div class="content-wrapper">
        <!-- 搜索和操作区域 -->
        <div class="search-bar">
            <el-button type="primary" @click="addStudent">添加学生</el-button>
            <el-button plain type="primary" @click="transferPersonnel">人员调度</el-button>
            <el-button plain type="primary" @click="importData">导入数据</el-button>
            <el-input
                v-model="searchForm.nameOrId"
                :prefix-icon="Search"
                class="search-input" clearable
                placeholder="姓名或学号查询"
            />
            <el-input
                v-model="searchForm.idCard"
                :prefix-icon="Search"
                class="search-input" clearable
                placeholder="身份证查询"
            />
            <el-select
                v-model="searchForm.status"
                class="search-select" clearable
                placeholder="请选择实名状态"
            >
              <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label" clearable
                  :value="item.value"
              />
            </el-select>
            <el-select
                v-model="searchForm.studentType"
                class="search-select"
                placeholder="学生类型" clearable
            >
              <el-option
                  v-for="item in studentTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value" clearable
              />
            </el-select>
          <div>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </div>
        </div>
        <!-- 右侧表格 -->
        <div class="table-container">
          <el-table :data="studentData" align="center" border style="width: 100%" empty-text="暂无数据">
            <el-table-column v-for="column in columns"
                             :key="column.prop"
                             :label="column.label"
                             :prop="column.prop"
                             :width="column.width" show-overflow-tooltip
                             align="center"
            >
              <template v-if="column.prop === 'avatar'" #default="scope" >
                <el-link type="primary" @click="handleClick(scope.row.userInfoVo.facePhoto)" v-if="scope.row.userInfoVo.facePhoto"> {{ scope.row.userInfoVo.id }}</el-link>
              </template>
              <template v-else-if="column.prop === 'realName'" #default="scope">
                <el-tag v-if="scope.row.orgDepartmentInfoVO.isRealName === 1" size="default" type="primary">已实名</el-tag>
                <el-tag v-else size="default" type="info">未实名</el-tag>
              </template>
              <template v-else-if="column.prop === 'gender'" #default="scope">
                {{ scope.row.gender === 0 ? '未填写' : (scope.row.gender === 1 ? '男' : '女') }}
              </template>
              <template v-else-if="column.prop === 'grade'" #default="scope">
                {{scope.row.orgDepartmentInfoVO.departName }}
              </template>
              <template v-else-if="column.prop === 'type'" #default="scope">
               {{ getTextByCode('studentType', scope.row.studentType, '未知') }}
              </template>

            </el-table-column>
            <el-table-column align="center" label="操作" width="120">
              <template #default="scope">
                <edit style="width: 20px;color: #99BFFF;margin-right: 10px" @click="editStudent(scope.row)"></edit>
                <delete style="width: 20px;color: red" @click="deleteStudent(scope.row)"></delete>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 -->
          <div class="pagination-container" v-if="pagination.total >0">
            <el-pagination
              v-model:current-page="pagination.pageNum"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[15, 20, 50, 100]"
              :layout="pagination.total === 1 ? 'prev, pager, next,total' : 'prev, pager, next,total,sizes'"
              :total="pagination.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              background
            />
          </div>
        </div>
      </div>
      <el-image-viewer
          v-if="showPreview"
          :url-list="[imageRef]"
          show-progress
          @close="showPreview = false"
      />
    </div>
    <el-dialog v-model="dialogFormVisible" title="" width="500px">
      <ImageUploader @on-cancel="dialogFormVisible = false"  field-name=""></ImageUploader>
    </el-dialog>
    <el-dialog v-model="DispatchVisible" title="人员调度" width="760px">
      <DispatchForm @on-cancel="DispatchVisible=false" :trbanji="schoolData"></DispatchForm>
    </el-dialog>
    <el-dialog v-model="structureDialogVisible" :title="structureDialogTitle" width="400px">
      <el-form :model="structureForm" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="structureForm.name" placeholder="请输入架构名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="structureDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleStructureSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>

.content-wrapper {
  padding: 20px;
  flex: 1;
  overflow: auto;
}
.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>
